package com.woniu108.gateway.exception;

import cn.hutool.json.JSONUtil;
import com.woniu108.gateway.model.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Result<?> result=Result.getResult().setCode(500).setMsg("出现异常");
        if(ex instanceof WoniuException){
            WoniuException me= (WoniuException) ex;
            result=Result.getResult().setCode(me.getCode()).setMsg(me.getMessage());
        }

        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String json= JSONUtil.parse(result).toString();
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }
}
